<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="参观场所" prop="venueId">
        <el-select v-model="queryParams.venueId" placeholder="请选择参观类型">
          <el-option
            v-for="venue in venueList"
            :key="venue.id"
            :label="venue.name"
            :value="parseInt(venue.id)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参观时间" prop="orderTime">
        <el-date-picker
          clearable
          v-model="queryParams.orderTime"
          type="datetime"
          value-format="yyyy-MM-dd hh:mm:ss"
          placeholder="请选择参观时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="参观类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择参观类型" clearable>
          <el-option
            v-for="dict in dict.type.group_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参观团名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入参观团名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="参观场所" align="center" prop="procuVenue.name"/>
      <el-table-column label="参观开始时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="参观结束时间"
        align="center"
        prop="orderEndTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderEndTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参观人数" align="center" prop="number"/>
      <el-table-column label="参观类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.group_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="参观团名称" align="center" prop="name"/>
      <el-table-column label="联系方式" align="center" prop="phone"/>
      <el-table-column label="姓名" align="center" prop="personName"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="资质文件" align="center">
        <template slot-scope="scope">
          <el-button
            type="mini"
            plain
            icon="el-icon-download"
            v-if="scope.row.qualification"
            @click="downloadFn(scope.row.qualification)"
          >下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否通过" align="center" width="100">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.is_Pass"
            placeholder="预约状态"
            v-if="scope.row.isPass == 2"
            @change="changePassFn(scope.$index)"
            size="small"
            style="width: 90px"
          >
            <el-option
              v-for="dict in isPassList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
          <dict-tag :options="dict.type.pass_not" :value="scope.row.isPass" v-else/>
        </template>
      </el-table-column>
      <el-table-column label="推送" align="center" prop="is_pass">
        <template slot-scope="scope">
          <el-button
            type="mini"
            plain
            icon="el-icon-upload2"
            @click="pushObject(scope.row.id)"
          >推送
          </el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" id="fromHeight">
        <el-form-item label="参观场所" prop="venueId">
          <el-select
            v-model="form.venueId"
            @change="getVenueDetail"
            placeholder="请选择参观类型"
          >
            <el-option
              v-for="venue in venueOpenList"
              :key="venue.id"
              :label="venue.name"
              :value="parseInt(venue.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参观日期" prop="orderTime">
          <el-date-picker
            clearable
            v-model="form.orderTime"
            :picker-options="pickerOptions"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择参观日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参观时间" prop="venueTime">
          <el-select v-model="form.venueTime" placeholder="请选择参观时间">
            <el-option
              v-for="venue in venueTimeList"
              :key="venue.id"
              :label="venue.openTime"
              :value="venue.openTime"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参观人数" prop="number">
          <el-input v-model="form.number" placeholder="请输入参观人数"/>
        </el-form-item>
        <el-form-item label="参观类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择参观类型">
            <el-option
              v-for="dict in dict.type.group_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参观团名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参观团名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="姓名" prop="personName">
          <el-input v-model="form.personName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资质文件">
          <file-upload v-model="form.qualification"/>
        </el-form-item>
        <el-form-item label="是否通过" prop="is_pass">
          <el-select v-model="form.isPass" placeholder="请选择通过或驳回">
            <el-option
              v-for="dict in dict.type.pass_not"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <div style="display: none">
      <iframe :src="fileSrc_" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  getPush,
} from "@/api/system/order";
import {getUserProfile} from "@/api/system/user";
import {listVenue, getVenue} from "@/api/system/venue";

export default {
  name: "Order",
  dicts: ["group_type", "sys_user_sex", "pass_not"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户userId
      userId: null,
      venueQueryParams: {
        pageNum: 1,
        pageSize: 500,
      },
      venueList: [],
      venueOpenList: [],
      venueTimeList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderTime: null,
        orderEndTime: null,
        type: null,
        name: null,
        phone: null,
        personName: null,
        sex: null,
        qualification: null,
        venueId: null,
      },
      isPassList: [
        {id: 1, name: "通过"},
        {id: 2, name: "驳回"},
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        venueId: [{required: true, message: "参观场所不能为空", trigger: "change"}],
        orderTime: [{required: true, message: "参观日期不能为空", trigger: "change"}],
        venueTime: [{required: true, message: "参观时间不能为空", trigger: "blur"}],
        number: [{required: true, message: "参观人数不能为空", trigger: "blur"}],
        name: [{required: true, message: "参观团名称不能为空", trigger: "blur"}],
        personName: [{required: true, message: "姓名不能为空", trigger: "blur"}],
        phone: [{required: true, message: "联系方式不能为空", trigger: "blur"}],
        sex: [{required: true, message: "性别不能为空", trigger: "change"}],
      },
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() < Date.now();
        },
      },
      fileSrc_: "",
      file_can_down: ["zip", "rar", "docx", "doc", "xlsx", "xls", "pdf"],
      file_preview: ["jpeg", "png", "jpg"],
    };
  },
  created() {
    this.getUser();
    this.getVenueList();
    this.getList();
  },
  methods: {
    /** 查询预约列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then((response) => {
        for (let item of response.rows) {
          item.is_Pass = "";
        }
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getVenueList() {
      listVenue(this.venueQueryParams).then((response) => {
        this.venueList = response.rows;
        this.venueOpenList = this.venueList.filter((item) => item.isOpen === 0);
      });
    },
    getVenueDetail(option) {
      console.log('变化信息===>')
      let that = this
      getVenue(this.form.venueId).then((response) => {
        this.venueTimeList = response.data.procuOpenTimeList;
        if (option == 'edit') {
          for (let item of response.data.procuOpenTimeList) {
            let a_ = item.openTime.split('-')
            if (a_[1] == this.form.venueTime) {
              that.$set(that.form, 'venueTime', item.openTime)
            }
          }
        }
      });
    },
    getUser() {
      getUserProfile().then((response) => {
        this.userId = response.data.userId;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: this.userId,
        orderTime: null,
        orderEndTime: null,
        venueTime: null,
        number: null,
        type: null,
        name: null,
        remarks: null,
        phone: null,
        personName: null,
        sex: null,
        qualification: null,
        createTime: null,
        venueId: null,
      };
      this.resetForm("form");
      this.venueTimeList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then((response) => {
        this.form = response.data;
        let a_ = response.data.orderEndTime.split(' ');
        let b_ = a_[1].split(':')
        b_.pop();
        let d_ = response.data.orderTime.split(' ');
        this.form.orderTime = d_[0]
        this.$set(this.form, 'venueTime', b_.join(':'))
        this.getVenueDetail('edit')
        this.open = true;
        this.title = "修改预约";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let option = JSON.parse(JSON.stringify(this.form))
          const venueTime = option.venueTime.split("-");
          const orderEndTime = option.orderTime.toString();
          option.orderTime = `${option.orderTime} ${venueTime[0]}:00`;
          option.orderEndTime = `${orderEndTime} ${venueTime[1]}:00`;
          if (option.id != null) {
            updateOrder(option).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(option).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除预约编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
    // 通过驳回
    changePassFn(index) {
      let n = this;
      let item_ = JSON.parse(JSON.stringify(this.orderList[index]));
      if (item_.is_Pass) {
        let title_ = Number(item_.is_Pass) === 1 ? "通过" : "驳回";
        this.$confirm(`此操作${title_}预约, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            getOrder(item_.id).then((response) => {
              // 0是预约失败，1是【根据时间判断已经参观还是未参观】，2是预约中
              response.data.isPass = 1;
              if (Number(item_.is_Pass) === 2) {
                response.data.isPass = 0;
              }
              n.submitApplyfn(response.data);
            });
          })
          .catch(() => {
            item_.is_Pass = "";
            n.$set(this.orderList, index, item_);
          });
      }
    },
    submitApplyfn(option) {
      updateOrder(option).then((response) => {
        console.log(response);
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    // 推送
    pushObject(id) {
      getPush(id).then((response) => {
        console.log("dfdf", response);
        if (response.code === 200 && response.data.errmsg !== "ok") {
          this.$message.error("用户未授权或已经推送过");
        }
        if (response.code === 200 && response.data.errmsg === "ok") {
          this.$message.success("推送成功");
        }
      });
    },
    // 下载文件
    downloadFn(option) {
      this.fileSrc_ = "";
      if (option) {
        let a = option.split(".");
        let type_ = a[a.length - 1];
        if (this.file_can_down.indexOf(type_) !== -1) {
          this.fileSrc_ = option;
        } else if (this.file_preview.indexOf(type_) !== -1) {
          this.downloadIamge(option, "资质文件");
        } else {
          this.$confirm(`该文件不可下载`, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          })
            .then(() => {
            })
            .catch(() => {
            });
        }
      }
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },
  },
};
</script>
